import { ref } from 'vue'

// 主题类型定义
export interface ThemeConfig {
  mode: 'light' | 'dark' | 'auto'
  primary: string
  layout: 'side' | 'top' | 'mix'
  features: string[]
}

// 默认主题配置
export const defaultTheme: ThemeConfig = {
  mode: 'light',
  primary: '#409EFF',
  layout: 'side',
  features: ['breadcrumb', 'tabs']
}

// 主题变量映射
const themeVars = {
  light: {
    '--el-bg-color': '#ffffff',
    '--el-bg-color-page': '#f2f3f5',
    '--el-text-color-primary': '#303133',
    '--el-text-color-regular': '#606266',
    '--el-border-color': '#dcdfe6'
  },
  dark: {
    '--el-bg-color': '#141414',
    '--el-bg-color-page': '#000000',
    '--el-text-color-primary': '#ffffff',
    '--el-text-color-regular': '#d0d0d0',
    '--el-border-color': '#434343'
  }
}

// 当前主题配置
export const currentTheme = ref<ThemeConfig>({...defaultTheme})

// 设置主题模式
export const setThemeMode = (mode: ThemeConfig['mode']) => {
  const html = document.documentElement
  
  if (mode === 'auto') {
    const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
    mode = prefersDark ? 'dark' : 'light'
    
    // 监听系统主题变化
    window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
      const newMode = e.matches ? 'dark' : 'light'
      applyThemeVars(newMode)
    })
  }
  
  applyThemeVars(mode)
  currentTheme.value.mode = mode
  localStorage.setItem('theme-mode', mode)
}

// 设置主题色
export const setThemePrimary = (color: string) => {
  const style = document.documentElement.style
  
  // 生成不同深浅的主题色
  const colors = generatePrimaryColors(color)
  
  // 设置主题色变量
  Object.entries(colors).forEach(([key, value]) => {
    style.setProperty(`--el-color-primary${key === 'primary' ? '' : `-${key}`}`, value)
  })
  
  currentTheme.value.primary = color
  localStorage.setItem('theme-primary', color)
}

// 设置布局模式
export const setThemeLayout = (layout: ThemeConfig['layout']) => {
  currentTheme.value.layout = layout
  localStorage.setItem('theme-layout', layout)
}

// 设置功能特性
export const setThemeFeatures = (features: string[]) => {
  currentTheme.value.features = features
  localStorage.setItem('theme-features', JSON.stringify(features))
}

// 初始化主题
export const initTheme = () => {
  // 从本地存储恢复主题设置
  const mode = localStorage.getItem('theme-mode') as ThemeConfig['mode'] || defaultTheme.mode
  const primary = localStorage.getItem('theme-primary') || defaultTheme.primary
  const layout = localStorage.getItem('theme-layout') as ThemeConfig['layout'] || defaultTheme.layout
  const features = JSON.parse(localStorage.getItem('theme-features') || JSON.stringify(defaultTheme.features))
  
  setThemeMode(mode)
  setThemePrimary(primary)
  setThemeLayout(layout)
  setThemeFeatures(features)
}

// 重置主题
export const resetTheme = () => {
  setThemeMode(defaultTheme.mode)
  setThemePrimary(defaultTheme.primary)
  setThemeLayout(defaultTheme.layout)
  setThemeFeatures(defaultTheme.features)
}

// 应用主题变量
const applyThemeVars = (mode: 'light' | 'dark') => {
  const style = document.documentElement.style
  const vars = themeVars[mode]
  
  // 设置主题变量
  Object.entries(vars).forEach(([key, value]) => {
    style.setProperty(key, value)
  })
  
  // 设置body类名
  document.body.className = mode
}

// 生成主题色的不同深浅
const generatePrimaryColors = (primary: string) => {
  // 这里使用简化的算法，实际项目中可以使用更复杂的算法
  const lighten = (color: string, amount: number) => {
    const rgb = hexToRgb(color)
    const hsl = rgbToHsl(rgb.r, rgb.g, rgb.b)
    hsl.l = Math.min(1, hsl.l + amount)
    const newRgb = hslToRgb(hsl.h, hsl.s, hsl.l)
    return rgbToHex(newRgb.r, newRgb.g, newRgb.b)
  }
  
  const darken = (color: string, amount: number) => {
    const rgb = hexToRgb(color)
    const hsl = rgbToHsl(rgb.r, rgb.g, rgb.b)
    hsl.l = Math.max(0, hsl.l - amount)
    const newRgb = hslToRgb(hsl.h, hsl.s, hsl.l)
    return rgbToHex(newRgb.r, newRgb.g, newRgb.b)
  }
  
  return {
    'primary': primary,
    'light-3': lighten(primary, 0.2),
    'light-5': lighten(primary, 0.3),
    'light-7': lighten(primary, 0.4),
    'light-9': lighten(primary, 0.5),
    'dark-2': darken(primary, 0.1)
  }
}

// 颜色转换工具函数
const hexToRgb = (hex: string) => {
  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
  return result ? {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16)
  } : { r: 0, g: 0, b: 0 }
}

const rgbToHex = (r: number, g: number, b: number) => {
  return '#' + [r, g, b].map(x => {
    const hex = x.toString(16)
    return hex.length === 1 ? '0' + hex : hex
  }).join('')
}

const rgbToHsl = (r: number, g: number, b: number) => {
  r /= 255
  g /= 255
  b /= 255
  
  const max = Math.max(r, g, b)
  const min = Math.min(r, g, b)
  let h = 0
  let s
  const l = (max + min) / 2
  
  if (max === min) {
    h = s = 0
  } else {
    const d = max - min
    s = l > 0.5 ? d / (2 - max - min) : d / (max + min)
    switch (max) {
      case r: h = (g - b) / d + (g < b ? 6 : 0); break
      case g: h = (b - r) / d + 2; break
      case b: h = (r - g) / d + 4; break
    }
    h /= 6
  }
  
  return { h, s, l }
}

const hslToRgb = (h: number, s: number, l: number) => {
  let r, g, b
  
  if (s === 0) {
    r = g = b = l
  } else {
    const hue2rgb = (p: number, q: number, t: number) => {
      if (t < 0) t += 1
      if (t > 1) t -= 1
      if (t < 1/6) return p + (q - p) * 6 * t
      if (t < 1/2) return q
      if (t < 2/3) return p + (q - p) * (2/3 - t) * 6
      return p
    }
    
    const q = l < 0.5 ? l * (1 + s) : l + s - l * s
    const p = 2 * l - q
    
    r = hue2rgb(p, q, h + 1/3)
    g = hue2rgb(p, q, h)
    b = hue2rgb(p, q, h - 1/3)
  }
  
  return {
    r: Math.round(r * 255),
    g: Math.round(g * 255),
    b: Math.round(b * 255)
  }
} 